#define  _CRT_SECURE_NO_WARNINGS
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (k == 1)return head;

        int len = 0;
        ListNode* cur = head;
        while (cur) len++, cur = cur->next;
        int n = len / k;

        ListNode guard, * tail = &guard;
        cur = head;
        while (n--)
        {
            ListNode* tmp = cur;

            for (int i = 0; i < k; i++)
            {
                ListNode* next = cur->next;
                cur->next = tail->next;
                tail->next = cur;
                cur = next;
            }
            tail = tmp;
        }
        tail->next = cur;
        return guard.next;
    }
};